package com.example.demo4;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class FruitsAdapter extends RecyclerView.Adapter<FruitsAdapter.ViewHolder> {
    private List<Fruit> fruitList;

    /**
     * 内部类
     */
    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView fruit_img;
        TextView fruit_name;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            fruit_img=itemView.findViewById(R.id.fruit_img);
            fruit_name=itemView.findViewById(R.id.fruit_name);
        }
    }

    public FruitsAdapter(List<Fruit> fruitList) {
        this.fruitList = fruitList;
    }

    @NonNull
    @Override
    public FruitsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        ViewHolder viewHolder=new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull FruitsAdapter.ViewHolder holder, int position) {
        Fruit fruit = fruitList.get(position);
        holder.fruit_img.setImageResource(fruit.getImageId());
        holder.fruit_name.setText(fruit.getName());
    }

    @Override
    public int getItemCount() {
        return fruitList.size();
    }


}
